import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios';
import { useAuth } from '../context/AuthContext';
import { Formik, Form, Field, ErrorMessage } from 'formik';
import * as Yup from 'yup';
import { FaPlus, FaSync, FaEdit, FaTrash, FaCheckCircle, FaExclamationTriangle, FaMagic } from 'react-icons/fa';
import '../styles/SourcesList.css';

const SourcesList = () => {
  const { user } = useAuth();
  const isAdmin = user?.role === 'admin';
  const [sources, setSources] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [showAddForm, setShowAddForm] = useState(false);
  const [monitorLoading, setMonitorLoading] = useState({});
  const [organizations, setOrganizations] = useState([]);
  const [selectedOrganization, setSelectedOrganization] = useState('');
  const [aiAnalysisLoading, setAiAnalysisLoading] = useState({});
  const [aiAnalysisResult, setAiAnalysisResult] = useState(null);

  // 获取采集源列表
  const fetchSources = async () => {
    try {
      setLoading(true);
      const res = await axios.get('/api/sources');
      setSources(res.data);
      
      // 提取不重复的组织列表
      const orgs = [...new Set(res.data.map(source => source.organization))];
      setOrganizations(orgs);
      
      setError(null);
    } catch (err) {
      console.error('获取采集源列表失败:', err);
      setError('获取采集源列表失败，请稍后再试');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchSources();
  }, []);

  // 过滤采集源
  const filteredSources = selectedOrganization 
    ? sources.filter(source => source.organization === selectedOrganization)
    : sources;

  // 手动监测采集源
  const handleMonitor = async (sourceId) => {
    try {
      setMonitorLoading(prev => ({ ...prev, [sourceId]: true }));
      await axios.post(`/api/sources/${sourceId}/monitor`);
      
      // 监测成功后刷新列表
      await fetchSources();
      
      setError(null);
    } catch (err) {
      console.error('监测采集源失败:', err);
      setError('监测采集源失败，请稍后再试');
    } finally {
      setMonitorLoading(prev => ({ ...prev, [sourceId]: false }));
    }
  };

  // 使用AI分析页面结构
  const handleAiAnalysis = async (sourceId, listUrl) => {
    try {
      setAiAnalysisLoading(prev => ({ ...prev, [sourceId]: true }));
      setAiAnalysisResult(null);
      
      const response = await axios.post(`/api/sources/${sourceId}/analyze-with-ai`, { url: listUrl });
      
      setAiAnalysisResult(response.data);
      
      // 自动填充分析结果到表单
      if (showAddForm && response.data) {
        // 如果当前正在添加新采集源，则填充到添加表单
        // 这部分在handleAiApplyToForm中实现
      }
      
      setError(null);
    } catch (err) {
      console.error('AI分析失败:', err);
      setError('AI分析失败，请稍后再试');
      setAiAnalysisResult(null);
    } finally {
      setAiAnalysisLoading(prev => ({ ...prev, [sourceId]: false }));
    }
  };
  
  // 应用AI分析结果到表单
  const handleAiApplyToForm = (formikProps) => {
    if (!aiAnalysisResult) return;
    
    const { setFieldValue } = formikProps;
    
    // 应用AI分析的选择器结果到表单
    if (aiAnalysisResult.selectors) {
      Object.entries(aiAnalysisResult.selectors).forEach(([key, value]) => {
        setFieldValue(`selectors.${key}`, value);
      });
    }
  };

  // 删除采集源
  const handleDelete = async (sourceId) => {
    if (!window.confirm('确定要删除这个采集源吗？这将删除相关的所有数据。')) {
      return;
    }
    
    try {
      await axios.delete(`/api/sources/${sourceId}`);
      
      // 删除成功后刷新列表
      await fetchSources();
      
      setError(null);
    } catch (err) {
      console.error('删除采集源失败:', err);
      setError('删除采集源失败，请稍后再试');
    }
  };

  // 添加采集源表单验证规则
  const validationSchema = Yup.object({
    name: Yup.string().required('名称为必填项'),
    organization: Yup.string().required('组织名称为必填项'),
    listUrl: Yup.string().url('请输入有效的URL').required('列表URL为必填项'),
    proxy: Yup.object({
      enabled: Yup.boolean(),
      host: Yup.string().when('enabled', {
        is: true,
        then: (schema) => schema.required('代理服务器地址为必填项'),
        otherwise: (schema) => schema
      }),
      port: Yup.number().when('enabled', {
        is: true,
        then: (schema) => schema.required('代理端口为必填项').min(1, '端口必须大于0').max(65535, '端口必须小于65536'),
        otherwise: (schema) => schema
      })
    })
  });

  // 处理表单提交
  const handleSubmit = async (values, { resetForm, setSubmitting }) => {
    try {
      await axios.post('/api/sources', values);
      
      // 添加成功后刷新列表
      await fetchSources();
      
      // 重置表单并关闭
      resetForm();
      setShowAddForm(false);
      setError(null);
    } catch (err) {
      console.error('添加采集源失败:', err);
      setError(err.response?.data?.message || '添加采集源失败，请稍后再试');
    } finally {
      setSubmitting(false);
    }
  };

  if (loading && sources.length === 0) {
    return <div className="loading">加载中...</div>;
  }

  return (
    <div className="sources-list-container">
      <div className="page-header">
        <h1>采集源管理</h1>
        <div className="header-actions">
          {isAdmin && (
            <button 
              className="add-button"
              onClick={() => setShowAddForm(!showAddForm)}
            >
              <FaPlus /> 添加采集源
            </button>
          )}
        </div>
      </div>

      {error && <div className="error-message">{error}</div>}

      {/* AI分析结果提示 */}
      {aiAnalysisResult && (
        <div className="ai-analysis-result">
          <h3>AI分析结果</h3>
          <p>DeepSeek AI已成功分析页面结构，找到以下选择器:</p>
          <ul>
            <li><strong>列表项选择器:</strong> {aiAnalysisResult.selectors?.listItemSelector || '未找到'}</li>
            <li><strong>姓名选择器:</strong> {aiAnalysisResult.selectors?.nameSelector || '未找到'}</li>
            <li><strong>职位选择器:</strong> {aiAnalysisResult.selectors?.positionSelector || '未找到'}</li>
            <li><strong>图片选择器:</strong> {aiAnalysisResult.selectors?.imageSelector || '未找到'}</li>
            <li><strong>详情链接选择器:</strong> {aiAnalysisResult.selectors?.detailLinkSelector || '未找到'}</li>
          </ul>
          <button 
            className="dismiss-button"
            onClick={() => setAiAnalysisResult(null)}
          >
            关闭
          </button>
        </div>
      )}

      {/* 添加采集源表单 */}
      {showAddForm && isAdmin && (
        <div className="add-source-form">
          <h2>添加新采集源</h2>
          <Formik
            initialValues={{
              name: '',
              organization: '',
              listUrl: '',
              detailUrlPattern: '',
              selectors: {
                listItemSelector: '',
                nameSelector: '',
                positionSelector: '',
                imageSelector: '',
                detailLinkSelector: ''
              },
              proxy: {
                enabled: false,
                host: '',
                port: ''
              }
            }}
            validationSchema={validationSchema}
            onSubmit={handleSubmit}
          >
            {({ isSubmitting, values, setFieldValue }) => (
              <Form>
                <div className="form-row">
                  <div className="form-group">
                    <label htmlFor="name">名称*</label>
                    <Field type="text" id="name" name="name" />
                    <ErrorMessage name="name" component="div" className="error" />
                  </div>
                  
                  <div className="form-group">
                    <label htmlFor="organization">组织名称*</label>
                    <Field type="text" id="organization" name="organization" />
                    <ErrorMessage name="organization" component="div" className="error" />
                  </div>
                </div>
                
                <div className="form-group url-with-analyze">
                  <label htmlFor="listUrl">列表页URL*</label>
                  <div className="url-input-group">
                    <Field type="text" id="listUrl" name="listUrl" />
                    <button
                      type="button"
                      className="ai-analyze-button"
                      onClick={() => values.listUrl && handleAiAnalysis('new', values.listUrl)}
                      disabled={!values.listUrl || aiAnalysisLoading['new']}
                      title="使用AI分析页面结构"
                    >
                      <FaMagic /> {aiAnalysisLoading['new'] ? '分析中...' : 'AI分析'}
                    </button>
                  </div>
                  <ErrorMessage name="listUrl" component="div" className="error" />
                </div>
                
                {aiAnalysisResult && (
                  <div className="ai-apply-action">
                    <button
                      type="button"
                      className="apply-ai-button"
                      onClick={() => handleAiApplyToForm({ setFieldValue })}
                    >
                      应用AI分析结果到表单
                    </button>
                  </div>
                )}
                
                <div className="form-group">
                  <label htmlFor="detailUrlPattern">详情页URL模式 (可选)</label>
                  <Field type="text" id="detailUrlPattern" name="detailUrlPattern" />
                  <small>例如: https://example.com/leaders/{'id'}</small>
                </div>
                
                {/* 代理设置 */}
                <div className="form-section">
                  <h3>代理设置</h3>
                  <div className="form-text">如果需要通过代理访问该数据源，请配置代理信息</div>
                  
                  <div className="form-group">
                    <div className="checkbox-group">
                      <Field type="checkbox" id="proxy.enabled" name="proxy.enabled" />
                      <label htmlFor="proxy.enabled">启用代理</label>
                    </div>
                  </div>
                  
                  {/* 启用代理后显示详细配置 */}
                  <Field name="proxy.enabled">
                    {({ field }) => field.value && (
                      <>
                        <div className="form-group">
                          <label htmlFor="proxy.host">代理服务器地址</label>
                          <Field type="text" id="proxy.host" name="proxy.host" placeholder="例如: 192.168.1.1" />
                          <ErrorMessage name="proxy.host" component="div" className="error" />
                        </div>
                        
                        <div className="form-group">
                          <label htmlFor="proxy.port">代理端口</label>
                          <Field type="number" id="proxy.port" name="proxy.port" placeholder="例如: 8080" />
                          <ErrorMessage name="proxy.port" component="div" className="error" />
                        </div>
                      </>
                    )}
                  </Field>
                </div>
                
                <h3>选择器配置 (可选)</h3>
                <div className="form-row">
                  <div className="form-group">
                    <label htmlFor="selectors.listItemSelector">列表项选择器</label>
                    <Field 
                      type="text" 
                      id="selectors.listItemSelector" 
                      name="selectors.listItemSelector" 
                    />
                  </div>
                  
                  <div className="form-group">
                    <label htmlFor="selectors.nameSelector">姓名选择器</label>
                    <Field 
                      type="text" 
                      id="selectors.nameSelector" 
                      name="selectors.nameSelector" 
                    />
                  </div>
                </div>
                
                <div className="form-row">
                  <div className="form-group">
                    <label htmlFor="selectors.positionSelector">职位选择器</label>
                    <Field 
                      type="text" 
                      id="selectors.positionSelector" 
                      name="selectors.positionSelector" 
                    />
                  </div>
                  
                  <div className="form-group">
                    <label htmlFor="selectors.imageSelector">图片选择器</label>
                    <Field 
                      type="text" 
                      id="selectors.imageSelector" 
                      name="selectors.imageSelector" 
                    />
                  </div>
                </div>
                
                <div className="form-group">
                  <label htmlFor="selectors.detailLinkSelector">详情链接选择器</label>
                  <Field 
                    type="text" 
                    id="selectors.detailLinkSelector" 
                    name="selectors.detailLinkSelector" 
                  />
                </div>
                
                <div className="form-actions">
                  <button type="submit" disabled={isSubmitting}>
                    {isSubmitting ? '提交中...' : '添加'}
                  </button>
                  <button type="button" onClick={() => setShowAddForm(false)}>
                    取消
                  </button>
                </div>
              </Form>
            )}
          </Formik>
        </div>
      )}

      {/* 筛选器 */}
      {organizations.length > 0 && (
        <div className="filters">
          <div className="filter-group">
            <label>按组织筛选:</label>
            <select 
              value={selectedOrganization} 
              onChange={(e) => setSelectedOrganization(e.target.value)}
            >
              <option value="">所有组织</option>
              {organizations.map(org => (
                <option key={org} value={org}>{org}</option>
              ))}
            </select>
          </div>
        </div>
      )}

      {/* 采集源列表 */}
      {filteredSources.length > 0 ? (
        <div className="sources-list">
          <table>
            <thead>
              <tr>
                <th>名称</th>
                <th>组织</th>
                <th>URL</th>
                <th>状态</th>
                <th>代理</th>
                <th>最后监测</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              {filteredSources.map(source => (
                <tr key={source._id} className={source.status === 'error' ? 'error-row' : ''}>
                  <td>
                    <Link to={`/sources/${source._id}`}>{source.name}</Link>
                  </td>
                  <td>{source.organization}</td>
                  <td>
                    <a href={source.listUrl} target="_blank" rel="noopener noreferrer">
                      {truncateUrl(source.listUrl)}
                    </a>
                  </td>
                  <td>
                    <span className={`status status-${source.status}`}>
                      {source.status === 'active' && <FaCheckCircle />}
                      {source.status === 'error' && <FaExclamationTriangle title={source.errorMessage} />}
                      {getStatusLabel(source.status)}
                    </span>
                  </td>
                  <td>
                    {source.proxy && source.proxy.enabled ? (
                      <span className="proxy-enabled" title={`${source.proxy.host}:${source.proxy.port}`}>
                        已启用
                      </span>
                    ) : (
                      <span className="proxy-disabled">未启用</span>
                    )}
                  </td>
                  <td>
                    {source.lastCrawled ? new Date(source.lastCrawled).toLocaleString() : '从未'}
                  </td>
                  <td className="actions">
                    <button 
                      className="action-button monitor-button" 
                      onClick={() => handleMonitor(source._id)}
                      disabled={monitorLoading[source._id]}
                      title="监测此采集源"
                    >
                      <FaSync className={monitorLoading[source._id] ? 'spinning' : ''} />
                    </button>
                    
                    <button 
                      className="action-button ai-analyze-button" 
                      onClick={() => handleAiAnalysis(source._id, source.listUrl)}
                      disabled={aiAnalysisLoading[source._id]}
                      title="使用AI分析页面结构"
                    >
                      <FaMagic className={aiAnalysisLoading[source._id] ? 'spinning' : ''} />
                    </button>
                    
                    <Link 
                      to={`/sources/${source._id}`} 
                      className="action-button edit-button"
                      title="编辑"
                    >
                      <FaEdit />
                    </Link>
                    
                    {isAdmin && (
                      <button 
                        className="action-button delete-button" 
                        onClick={() => handleDelete(source._id)}
                        title="删除"
                      >
                        <FaTrash />
                      </button>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      ) : (
        <div className="no-data">
          {selectedOrganization 
            ? `没有找到属于 "${selectedOrganization}" 的采集源` 
            : '没有采集源数据，请添加新的采集源'
          }
        </div>
      )}
    </div>
  );
};

// 状态标签
const getStatusLabel = (status) => {
  const statusMap = {
    'active': '活跃',
    'inactive': '不活跃',
    'error': '错误'
  };
  
  return statusMap[status] || status;
};

// 截断URL
const truncateUrl = (url) => {
  if (!url) return '';
  return url.length > 40 ? url.substring(0, 37) + '...' : url;
};

export default SourcesList; 